<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">

      <el-row>
        <el-col :span="8">
          <el-form-item label="故障标题" prop="reportTitle">
            <el-input v-model="form.reportTitle" placeholder="请输入故障标题"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="故障大类" prop="reportTypeBig">
            <el-select v-model="form.reportTypeBig" filterable placeholder="请输入故障大类" @change="reportTypeBigChange">
              <el-option
                v-for="item in reportTypeBigList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="故障小类" prop="reportTypeSmall">
            <el-select v-model="form.reportTypeSmall" filterable placeholder="请输入故障小类">
              <el-option
                v-for="item in reportTypeSmallList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="qq号" prop="qq">
            <el-input v-model="form.qq" placeholder="请输入qq号"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="故障地点" prop="reportLocation">
            <el-input v-model="form.reportLocation" placeholder="请输入故障地点"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">

        </el-col>
      </el-row>
      <el-form-item label="故障描述" prop="reportDesc">
        <el-input v-model="form.reportDesc" type="textarea" placeholder="请输入内容"/>
      </el-form-item>
      <el-form-item label="上传附件" prop="reportFiles" style="width: 50%">
        <!--        <el-input v-model="form.reportFiles" type="textarea" placeholder="请输入内容"/>-->
        <el-upload
          class="upload-demo"
          :action="imgUpload.uploadUrl"
          :headers="imgUpload.headers"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          multiple
          :on-preview="handlePreview"
          :on-success="handleSuccess"
          :on-error="handleError"
          :on-exceed="handleExceed"
          :file-list="fileList">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: center">
      <el-button type="primary" size="small" @click="submitForm">提 交</el-button>
    </div>
  </div>
</template>

<script>
import {addReportOrder, getReportOrder, updateReportOrder} from "@/api/report/ReportOrder";
import {parseTime} from "@/utils/ruoyi";
import request from "@/utils/request";
import {getToken} from "../../../utils/auth";

export default {
  name: "ReportOrderComp",
  dicts: ['report_status'],
  data() {
    return {
      imgUpload: {
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken()
        },
        // 图片上传的方法地址:
        uploadUrl: process.env.VUE_APP_BASE_API + "/report/ReportOrder/upload", // 上传的图片服务器地址
        url2: process.env.VUE_APP_BASE_API,
      },
      // 表单参数
      form: {
        reportTypeSmall: "",
        uploadFiles: [],
        reportTypeSmallName: "",
        reportTypeBigName: ""
      },
      // 表单校验
      rules: {
        reportLocation: [
          {required: true, message: "故障地点不能为空", trigger: "blur"}
        ],
        reportTitle: [
          {required: true, message: "标题不能为空", trigger: "blur"}
        ],
        reportTypeBig: [
          {required: true, message: "故障大类不能为空", trigger: "change"}
        ],
        phone: [
          {required: true, message: "手机号不能为空", trigger: "change"}
        ],
        reportTypeSmall: [
          {required: true, message: "故障小类不能为空", trigger: "change"}
        ],
        reportDesc: [
          {required: true, message: "故障描述不能为空", trigger: "blur"}
        ],
      },
      reportTypeBigList: [],
      reportTypeSmallList: [],
      fileList: []
    }
  },
  created() {
    this.getReportTypeByPid(0).then(res => {
      this.reportTypeBigList = res.data
    })
    let id = this.$route.query.id
    if (id) {
      //查询信息
      getReportOrder(id).then(res => {
        this.form = res.data
        if (!this.form.uploadFiles) {
          this.form.uploadFiles = []
        }
        //拼接FileList
        var reportFiles = res.data.reportFiles
        var fileList = []
        if (reportFiles) {
          var fileArr = reportFiles.split(";")
          this.form.uploadFiles = fileArr
          for (var imgPath of fileArr) {
            var fileName = imgPath.substring(imgPath.lastIndexOf("/") + 1)
            fileList.push({
              "url": imgPath,
              "name": fileName
            })
          }
        }
        this.fileList = fileList;
        this.getReportTypeByPid(res.data.reportTypeBig).then(res => {
          this.reportTypeSmallList = res.data
        })
      })
    } else {
      // this.form.reportId = parseTime(new Date(), "{y}{m}{d}{h}{i}{s}{l}")
    }

  },
  methods: {
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$modal.loading("正在保存...");
          if (this.form.id != null) {
            updateReportOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.$store.dispatch("tagsView/delView", this.$route);
              this.$router.push({path: "/report/ReportOrder?refresh=true"});
              this.$modal.closeLoading()
            });
          } else {
            addReportOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.$store.dispatch("tagsView/delView", this.$route);
              this.$router.push({path: "/report/ReportOrder?refresh=true"});
              this.$modal.closeLoading()
            });
          }
        }
      });
    },
    reportTypeBigChange(id) {
      this.getReportTypeByPid(id).then(res => {
        this.reportTypeSmallList = res.data
        this.form.reportTypeSmall = ""
      })
    },
    getReportTypeByPid(pid) {
      //获取故障大类
      return request({
        url: '/report/ReportType/query/' + pid,
        method: 'get'
      })
    },
    handleRemove(file, fileList) {
      var fileName
      if (file.response) {
        fileName = file.response.fileName
      } else {
        fileName = file.url
      }
      this.form.uploadFiles.splice(this.form.uploadFiles.indexOf(fileName), 1)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleError(res, file) {
    },
    handleSuccess(res, file, fileList) {
      console.log(res)
      if (res.code == 500) {
        this.$message.error(res.msg)
        fileList.splice(fileList.findIndex(item => item == file), 1)
      } else {
        this.form.uploadFiles.push(res.data.path)
      }
    },
    handlePreview(file) {
      var fileName
      console.log(file)
      if (file.response) {
        fileName = file.response.data.path
      } else {
        var url = file.url
        fileName = url
      }
      var a = document.createElement("a")
      a.setAttribute("href", process.env.VUE_APP_BASE_API + "/file/download?path=" + fileName)
      a.setAttribute("download", fileName.substring(fileName.lastIndexOf("/")))
      a.setAttribute("target", "_blank")
      let clickEvent = document.createEvent("MouseEvents");
      clickEvent.initEvent("click", true, true);
      a.dispatchEvent(clickEvent);
    },
  }
}
</script>
